package pigshare.beans;

import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.primefaces.model.DefaultStreamedContent;

import pigshare.database.DatabaseManager;
import pigshare.objects.Foto;

@ManagedBean
@RequestScoped
public class TableBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String cookieValue;

	private List<Foto> fotos = new ArrayList<Foto>();

	private Foto selectedFoto;
	private Blob bl;
	private InputStream stream;
	private DefaultStreamedContent content;

	private Logger log = Logger.getLogger(LoginBean.class);
	
	public TableBean() throws SQLException, NamingException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		Cookie[] cookies = httpServletRequest.getCookies();

		if (cookies != null) {
			for (int j = 0; j < cookies.length; j++) {
				if (cookies[j].getName().equalsIgnoreCase("id")) {
					cookieValue = cookies[j].getValue();
				}
			}
		}
		getFotosOfUser(fotos, cookieValue);

	}

	public Foto getSelectedFoto() {
		return selectedFoto;
	}

	public void setSelectedFoto(Foto selectedFoto) {
		this.selectedFoto = selectedFoto;
	}

	private void getFotosOfUser(List<Foto> list, String id)
			throws SQLException, NamingException {
		String sql = "SELECT * FROM posts WHERE user_FK = '" + id + "';";
		ResultSet rs = DatabaseManager.getDatabaseManager().sendQuery(sql);
		while (rs.next()) {
			Foto foto = new Foto();
//			foto.setContent(content);
			foto.setContent(null);
			foto.setId(rs.getInt("id"));
			foto.setTitle(rs.getString("titel"));
			foto.setKommentar(rs.getString("kommentar"));
			foto.setPic(rs.getBlob("blob"));
			foto.setRating(rs.getInt("rating"));
			foto.setUser_FK(rs.getInt("user_FK"));
			list.add(foto);
		}
		fotos = list;
		log.info("size of the list of images of the user with the id " + cookieValue + " " + fotos.size() + " == " + list.size());
	}

	public List<Foto> getFotos() {
		return fotos;
	}

}